/*
 * Copyright (c) 2013 Mobs & Geeks
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the
 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.mobsandgeeks.adapters;

import ohos.aafwk.ability.Ability;
import ohos.agp.components.BaseItemProvider;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;

import java.util.List;

/**
 * 通过将模型中的Instant注释方法映射到布局上的 {@link ohos.agp.components.Component} 来构建自定义 {Adapter} 的类。可以使用 {@link InstantText} 注释来注释方法
 *
 * @param <T> T
 * @since 2021-06-30
 */
public class InstantAdapter<T> extends BaseItemProvider {
    private List<T> list;
    private Class<T> mDataType;
    private InstantAdapterCore instantAdapterCore;

    /**
     * 构造参数
     *
     * @param fractionAbility
     * @param layoutListLayout
     * @param bookClass
     * @param allBooks
     */
    public InstantAdapter(Ability fractionAbility, int layoutListLayout, Class<T> bookClass, List<T> allBooks) {
        this.list = allBooks;
        this.mDataType = bookClass;
        instantAdapterCore = new InstantAdapterCore(fractionAbility, this, layoutListLayout,
                mDataType);
    }

    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    @Override
    public Object getItem(int position) {
        Object object = null;
        if (list != null && position >= 0 && position < list.size()) {
            object = list.get(position);
        }
        return object;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public Component getComponent(int position, Component component, ComponentContainer componentContainer) {
        final Component cpt;
        if (component == null) {
            cpt = instantAdapterCore.createNewView(componentContainer);
        } else {
            cpt = component;
        }
        T instance = list.get(position);
        instantAdapterCore.bindToView(componentContainer, cpt, instance, position);
        return cpt;
    }
}
